//
//  V2NotificationViewController.m
//  v2ex-iOS
//
//  Created by Singro on 4/5/14.
//  Copyright (c) 2014 Singro. All rights reserved.
//

#import "JrdMeViewController.h"
#import "JrdCommon.h"
#import "JRDMeTableAccountCell.h"
#import "UIColor-Adaptive.h"
#import "UIColor+JRDNote.h"
#import "JrdAccountModel.h"
#import "MJRefresh.h"
#import "JrdAccountViewController.h"
#import "JrdQuestionViewController.h"
#import "JrdAccountExtViewController.h"
#import "JrdLearnCenterViewController.h"
#import "JrdChangeAccountViewController.h"
#import "JrdUserModel.h"
#import "JrdDatamanager.h"
//#define PROFILE_CHANGE_PHOTO 0
#define ME_LEARN_STATIS 0
#define ME_ACCOUNT 1
#define ME_TEST 2
#define TABLE_CELL_HEITHG 45
//#define PROFILE_PHONE_NUM 2

@interface JrdMeViewController () <UITableViewDataSource, UITableViewDelegate, UIViewControllerPreviewingDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,  UIImagePickerControllerDelegate>{
    JrdUserModel* user;
}
@property (nonatomic, assign) NSInteger pageCount;
@property (nonatomic, copy) void (^getNotificationListBlock)(NSUInteger page);
@property (nonatomic, strong) SCBarButtonItem *leftBarItem;
@property(strong, nonatomic) UIImageView *photoImageView;
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) NSString* imagePath;
@end

@implementation JrdMeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

        self.pageCount = 1;
        
    }
    return self;
}

- (void)initData{
    user = [JrdDatamanager manager].user;
}

- (void)loadView {
    [super loadView];
    [self initData];
    [self configureTableView];
    [self configureNavibarItems];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.sc_navigationItem.leftBarButtonItem = self.leftBarItem;
    
    //image picker
    //获取Documents文件夹目录
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path objectAtIndex:0];
    //指定新建文件夹路径
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    //保存图片的路径
    self.imagePath = [imageDocPath stringByAppendingPathComponent:@"image.png"];
    
    self.view.backgroundColor = [UIColor colorWithWhite:0.90 alpha:1.000];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.sc_navigationItem.title = NSLocalizedString(@"v2_me",nil);//@"我们学习";
    

}

#pragma mark - Layout

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
}

#pragma mark - Configure Views & blocks

- (void)configureNavibarItems {
    self.leftBarItem = [[SCBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico-menu"] highlight:[UIImage imageNamed:@"ico-menu"] style:SCBarButtonItemStylePlain handler:^(id sender) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowMenuNotification object:nil];
    }];
    
}

- (void)configureTableView {
    self.tableView                 = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - (NAVIGATION_BAR_HEIGHT))];
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate        = self;
    self.tableView.dataSource      = self;
    self.tableView.scrollEnabled  = NO;
    self.tableView.backgroundColor = JrdBackgroundColor;//JRD_RGB(240, 240, 240);
    [self.view addSubview:self.tableView];
}

#pragma mark - TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;//return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(JRD_CHECK_VALUE== [[JrdDatamanager manager] getCheckValue]){
        return 1;
    }else{
        return V2_ME_TABLE_COUNT;//self.notificationList.list.count;

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return TABLE_CELL_HEITHG;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }


        if(0 == indexPath.row){
            UIView *headerLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
            headerLineView.backgroundColor = JrdSpeLineColor;
            [cell addSubview:headerLineView];
        }
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10, (TABLE_CELL_HEITHG - 0.5), SCREEN_WIDTH - 10, 0.5)];
        lineView.backgroundColor = JrdSpeLineColor;
        [cell addSubview:lineView];


        UIFont *myFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:17.0];
        cell.textLabel.font = myFont;
        [cell.textLabel setTextColor:[UIColor blackColor]];
        cell.detailTextLabel.font = myFont;
        cell.detailTextLabel.textColor = Jrd9BColor;//[UIColor JRDColorStandardBlue];
        switch (indexPath.row) {
            case  ME_LEARN_STATIS:
            {
                cell.textLabel.text = NSLocalizedString(@"v2_learn_statistics", nil);
            }
                break;
            case  ME_ACCOUNT:
            {
                cell.textLabel.text = NSLocalizedString(@"v2_Account", nil);
            }
                break;
            case ME_TEST:
            {
                cell.textLabel.text = NSLocalizedString(@"jrd_test", nil);
            }break;
        }
        //cell.imageView.image = [UIImage imageNamed:@"icon_setting"];
        cell.backgroundColor = JrdWhite1Color;//[UIColor whiteColor];//JRD_RGB(240, 240, 240);
        [cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
        //[cell.layer setMasksToBounds:YES];
        //cell.layer.cornerRadius =5;
        return cell;

    //}
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    switch (indexPath.row) {
        case ME_TEST:{
            JrdQuestionViewController* jrdQuestion = [[JrdQuestionViewController alloc] init];
            [self.navigationController pushViewController:jrdQuestion animated:YES];
        }
            break;
        case ME_ACCOUNT:{
            JrdChangeAccountViewController* jrdQuestion = [[JrdChangeAccountViewController alloc] init];
            [self.navigationController pushViewController:jrdQuestion animated:YES];

        }break;
        case ME_LEARN_STATIS:{
            JrdLearnCenterViewController* jrdQuestion = [[JrdLearnCenterViewController alloc] init];
            [self.navigationController pushViewController:jrdQuestion animated:YES];

        }break;
        default:
            break;
    }
}

#pragma mark - Nofitications
- (void)didReceiveUpdateCheckInBadgeNotification {
    
    /*if ([V2CheckInManager manager].isExpired && kSetting.checkInNotiticationOn) {
        self.leftBarItem.badge = @"";
    } else {
        self.leftBarItem.badge = nil;
    }*/
    
}

- (void)loadNewData{
    //use fake data,
    [self.tableView.mj_header endRefreshing];
}
-(void)setupTableview{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //设置普通状态的动画图片
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=60; ++i) {
        //        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_anim__000%zd",i]];
        //        [idleImages addObject:image];
        UIImage *image = [UIImage imageNamed:@"icon_listheader_animation_1"];
        [idleImages addObject:image];
    }
    [header setImages:idleImages forState:MJRefreshStateIdle];
    
    //设置即将刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    UIImage *image1 = [UIImage imageNamed:@"icon_listheader_animation_1"];
    [refreshingImages addObject:image1];
    UIImage *image2 = [UIImage imageNamed:@"icon_listheader_animation_2"];
    [refreshingImages addObject:image2];
    [header setImages:refreshingImages forState:MJRefreshStatePulling];
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
    self.tableView.mj_header = header;
    //马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}


- (void)changeImage{
    NSLog(@"tap to change image");
    UIActionSheet *myActionSheet = [[UIActionSheet alloc]
                                    initWithTitle:nil
                                    delegate:self
                                    cancelButtonTitle:@"取消"
                                    destructiveButtonTitle:nil
                                    otherButtonTitles: @"从相册选择", @"拍照",nil];
    [myActionSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            //从相册选择
            [self LocalPhoto];
            break;
        case 1:
            //拍照
            [self takePhoto];
            break;
        default:
            break;
    }
}

//从相册选择
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    //[self.navigationController pushViewController:picker animated:YES];
    //[self presentModalViewController:picker animated:YES];
    //[self.view addSubview:picker.view];
    [self presentViewController:picker animated:YES completion:^{
        picker.delegate = self;
    }];
}

//拍照
-(void)takePhoto{
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:^{
            picker.delegate = self;
        }];//[self.navigationController pushViewController:picker animated:YES];
    }else {
        NSLog(@"该设备无摄像头");
    }
}

//图像选取器的委托方法，选完图片后回调该方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    
    //当图片不为空时显示图片并保存图片
    if (image != nil) {
        //图片显示在界面上
        /*[changeImg setBackgroundImage:image forState:UIControlStateNormal];
        
        //以下是保存文件到沙盒路径下
        //把图片转成NSData类型的数据来保存文件
        NSData *data;
        //判断图片是不是png格式的文件
        if (UIImagePNGRepresentation(image)) {
            //返回为png图像。
            data = UIImagePNGRepresentation(image);
        }else {
            //返回为JPEG图像。
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        //保存
        [[NSFileManager defaultManager] createFileAtPath:self.imagePath contents:data attributes:nil];*/
        [self.tableView reloadData];
        
    }
    //关闭相册界面
    [picker popViewControllerAnimated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    if (info != nil) {
        UIImage* original_image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;

        //判断图片是不是png格式的文件
        if (UIImagePNGRepresentation(original_image)) {
            //返回为png图像。
            data = UIImagePNGRepresentation(original_image);
        }else {
            //返回为JPEG图像。
            data = UIImageJPEGRepresentation(original_image, 1.0);
        }
        //保存
        [[NSFileManager defaultManager] createFileAtPath:self.imagePath contents:data attributes:nil];
        [self.tableView reloadData];
    }

    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"cancel to pick controller");
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.size.width, 10)];
    headerView.backgroundColor = JrdTableHeadColor;//[UIColor clearColor];
    return headerView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView* footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.size.width, 5)];
    footView.backgroundColor = [UIColor clearColor];
    return footView;
    
}


@end
